﻿using KPIS.GERP.Models.Class;
using System;
using System.Linq;
using System.Web.Mvc;
using Resources;
using KPIS.GERP.Models.ICM;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class PrePurchaseItemController : Controller
    {
        public ActionResult Index(int pprId, bool emptyLayout = false)
        {
            var sPprI = new PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();
            var sPpr = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
            PrePurchaseRequest modelPpr = sPpr.Select(new PrePurchaseRequest { PprId = pprId }, null).FirstOrDefault();
            PrePurchaseRequestItem[] model = sPprI.Select(new PrePurchaseRequestItem { PprId = pprId }, new[]
            {
                "MasResourceItem", 
                "ProjectOperationExpense.ProjectExpense.MasBudgetSource",
                "ProjectOperationExpense.ProjectExpense.Project",
                "ProjectOperationExpense.ProjectOperation"
            });

            // Validate#1
            if(modelPpr == null)
            {
                return HttpNotFound("ไม่พบข้อมูลแจ้งความประสงค์ PprId = " + pprId);
            }
            
            ViewBag.PprId = pprId;
            ViewBag.PrePurchaseRequest = modelPpr;
            ViewBag.EmptyLayout = emptyLayout;
            ViewBag.bEditable = modelPpr.RecordStatus == Models.SYS.RecordStatus.WaitStatus || 
                modelPpr.RecordStatus == Models.SYS.RecordStatus.ReturnedStatus;

            return View(model);
        }

        public ActionResult Details(int Id)
        {
            var sPprI = new PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();
            var model = sPprI.Select(new Models.ICM.PrePurchaseRequestItem { PprItemId = Id }, new[] {
                "PrePurchaseRequest.MasPurchaseType"
                , "PrePurchaseRequest.YearType"
                , "ProjectOperationExpense.ProjectOperation"
                , "ProjectOperationExpense.ProjectExpense.MasBudgetExpense"
                , "ProjectOperationExpense.ProjectExpense.MasBudgetSource"
                , "MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType"
                , "MasResourceItem.MasUnit" }).FirstOrDefault();

            ViewBag.PcTypeId = model.PrePurchaseRequest.PcTypeId;
            ViewBag.PcTypeName = model.PrePurchaseRequest.MasPurchaseType.PcTypeName;
            ViewBag.YearTypeName = model.PrePurchaseRequest.YearType.YearTypeName;
            ViewBag.BgYear = model.PrePurchaseRequest.BgYear;
            ViewBag.bEditable = model.PrePurchaseRequest.RecordStatus == KPIS.GERP.Models.SYS.RecordStatus.WaitStatus || model.PrePurchaseRequest.RecordStatus == KPIS.GERP.Models.SYS.RecordStatus.ReturnedStatus;
            
            return View(model);
        }

        public ActionResult Create(int PprId)
        {
            var sPpr = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
            var modelMain = sPpr.Select(new Models.ICM.PrePurchaseRequest { PprId = PprId }, new[] { "YearType", "MasPurchaseType" }).FirstOrDefault();
            var model = new PrePurchaseRequestItem();
            model.PprId = PprId;
            model.HaveItem = true;

            ViewBag.PcTypeId = modelMain.PcTypeId;
            ViewBag.PcTypeName = modelMain.MasPurchaseType.PcTypeName;
            ViewBag.YearTypeName = modelMain.YearType.YearTypeName;
            ViewBag.BgYear = modelMain.BgYear;
            ViewBag.ModelPrePurchase = modelMain;

            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Create(PrePurchaseRequestItem model)
        {
            ModelState["MasResourceItem.MasUnit.Name"].Errors.Clear();

            if (ModelState.IsValid )
            {
                try
                {
                    var sProjOperExp = new ProjectOperationService.ProjectOperationServiceClient();
                    var sMaster = new IcmMasterService.IcmMasterServiceClient();
                    var sPpr = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
                    var sPprI = new PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();
                    model.MasResourceItem = null;//model.ResItemId.Value;
                    model.ProjectOperationExpense = null;//model.ProjOperExpId.Value;
                    var modelProjectExpense = sProjOperExp.SelectExpense(new Models.BGM.ProjectOperationExpense() { ProjOperExpId = model.ProjOperExpId.GetValueOrDefault(-1) }, new[] { "ProjectExpense" }).FirstOrDefault().ProjectExpense;
                    model.BgSourceId = modelProjectExpense.BgSourceId;
                    model.BgExpId = modelProjectExpense.BgExpId;
                    var rm = sMaster.SelectPurchaseRegularMapping(new MasPurchaseRegularMapping() { BgSourceId = model.BgSourceId }, null)
                        .FirstOrDefault();
                    model.RegularId = rm != null ? rm.RegularId : null;
                    if (model.ProjOperExpId == null ||
                        model.Qty == 0 || 
                        /*model.StdPrice == 0 || */
                        model.Price == 0 || 
                        (model.HaveItem == true && model.ResItemId == 0))
                    {
                        var modelMain2 = sPpr.Select(new PrePurchaseRequest { PprId = model.PprId }, new[] { "YearType", "MasPurchaseType" }).FirstOrDefault();
                        ViewBag.ModelPrePurchase = modelMain2;

                        string errorMissingInfo = "พบข้อผิดพลาด!! กรุณากรอกข้อมูลให้ครบถ้วน";
                        if (model.ProjOperExpId == null)
                        {
                            errorMissingInfo += "(กรุณาเลือกโครงการ)";
                        } if (model.Qty == 0)
                        {
                            errorMissingInfo += "(ระบุจำนวน)";
                        } if (model.Price == 0)
                        {
                            errorMissingInfo += "(ระบุราคาต่อหน่วย)";
                        }
                        if ((model.HaveItem == true && model.ResItemId == 0))
                        {
                            errorMissingInfo += "(เลือกรายการพัสดุ)";
                        }
                        ModelState.AddModelError("", errorMissingInfo);
                        return View(model);
                    }

                    if (rm == null || model.RegularId == null)
                    {
                        var modelMain2 = sPpr.Select(new PrePurchaseRequest { PprId = model.PprId }, new[] { "YearType", "MasPurchaseType" }).FirstOrDefault();
                        ViewBag.ModelPrePurchase = modelMain2;

                        ModelState.AddModelError("", "พบข้อผิดพลาด!! กรุณาตรวจสอบข้อมูลพื้นฐานระเบียบการซื้อจ้าง");
                        return View(model);
                    }

                    if (!model.HaveItem ?? true)
                    {
                        if (model.Descr == null || model.Descr.Trim().Length == 0)
                        {
                            ModelState.AddModelError("", "ข้อมูลไม่ถูกต้อง!! กรุณากรอกข้อมูล [รายละเอียด]");
                            return View(model);
                        }

                        model.MasResourceItem = null;
                        model.ResItemId = null;
                    }

                    if (!sPprI.CheckAmount(model.PprId))
                    {
                        ModelState.AddModelError("", "จำนวนเงินไม่ถูกต้อง!! จำนวนเงินที่ขอมากกว่าจำนวนเงินที่เหลือในขออนุมัติดำเนินงาน");
                        return View(model);
                    }

                    int intPprItemId = sPprI.Insert(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { Id = intPprItemId });
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
             
            var modelMain = new PrePurchaseRequestService.PrePurchaseRequestServiceClient().Select(new Models.ICM.PrePurchaseRequest { PprId = model.PprId }, new[] { "YearType", "MasPurchaseType" }).FirstOrDefault(); 
            ViewBag.ModelPrePurchase = modelMain;

            return View(model);
        }

        public ActionResult Edit(int Id)
        {
            var sPprI = new PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();
            var model = sPprI.Select(new Models.ICM.PrePurchaseRequestItem { PprItemId = Id }, new[] {
                "PrePurchaseRequest.MasPurchaseType"
                , "PrePurchaseRequest.YearType"
                , "ProjectOperationExpense.ProjectOperation"
                , "ProjectOperationExpense.ProjectExpense.MasBudgetExpense"
                , "MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType"
                , "MasResourceItem.MasUnit" }).FirstOrDefault();

            ViewBag.PcTypeId = model.PrePurchaseRequest.PcTypeId;
            ViewBag.PcTypeName = model.PrePurchaseRequest.MasPurchaseType.PcTypeName;
            ViewBag.YearTypeName = model.PrePurchaseRequest.YearType.YearTypeName;
            ViewBag.BgYear = model.PrePurchaseRequest.BgYear;
            ViewBag.ModelPrePurchase = model.PrePurchaseRequest;

            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Edit(int Id, PrePurchaseRequestItem model)
        {
            ModelState["MasResourceItem.MasUnit.Name"].Errors.Clear();

            var sPprI = new PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();
            var model2 = sPprI.Select(new Models.ICM.PrePurchaseRequestItem { PprItemId = Id }, new[] {
                "PrePurchaseRequest.MasPurchaseType"
                , "PrePurchaseRequest.YearType"
                , "ProjectOperationExpense.ProjectOperation"
                , "ProjectOperationExpense.ProjectExpense.MasBudgetExpense"
                , "MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType"
                , "MasResourceItem.MasUnit" }).FirstOrDefault();
            ViewBag.ModelPrePurchase = model2.PrePurchaseRequest;
            try
            {
                if (ModelState.IsValid)
                {
                    var sProjOperExp = new ProjectOperationService.ProjectOperationServiceClient();
                    var sMaster = new IcmMasterService.IcmMasterServiceClient(); 
                    model.MasResourceItem = null;//model.ResItemId.Value;
                    model.ProjectOperationExpense = null;//model.ProjOperExpId.Value;
                    var modelProjectExpense = sProjOperExp.SelectExpense(new Models.BGM.ProjectOperationExpense() { ProjOperExpId = model.ProjOperExpId.GetValueOrDefault(-1) , RecordStatus = "!D"}, new[] { "ProjectExpense" }).FirstOrDefault().ProjectExpense;
                    model.BgSourceId = modelProjectExpense.BgSourceId;
                    model.BgExpId = modelProjectExpense.BgExpId;
                    model.RegularId = sMaster.SelectPurchaseRegularMapping(new MasPurchaseRegularMapping() { BgSourceId = model.BgSourceId, RecordStatus = "!D" }, null)
                        .FirstOrDefault().RegularId;

                    if (model.RegularId == null)
                    {
                        ModelState.AddModelError("", "พบข้อผิดพลาด!! กรุณาตรวจสอบข้อมูลพื้นฐานระเบียบการซื้อจ้าง");
                        return View(model);
                    }

                    if (!model.HaveItem ?? true)
                    {
                        if (model.Descr == null || model.Descr.Trim().Length == 0)
                        {
                            ModelState.AddModelError("", "ข้อมูลไม่ถูกต้อง!! กรุณากรอกข้อมูล [รายละเอียด]");
                            return View(model);
                        }

                        model.MasResourceItem = null;
                        model.ResItemId = null;
                    }

                    sPprI.Update(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { Id = model.PprItemId });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(model);
        }


		public ActionResult Delete(int Id, int PprId)
		{
			try
			{
                var sPprI = new PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();
                sPprI.Delete(Id, Class.GimsMembership.CurrentEmpId);
				sPprI.Close();
                return RedirectToAction("Index", new { PprId = PprId });
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

		[HttpPost, ValidateAntiForgeryToken]
		public ActionResult DeleteAll(int[] deleteIds)
		{
			if (deleteIds == null)
				return Json(new { success = true });

			try
			{
                var sPprI = new PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();
				foreach (int delete in deleteIds)
				{
                    sPprI.Delete(delete, Class.GimsMembership.CurrentEmpId);
				}

				ModelState.AddModelError(ErrorLocalization.Error, string.Format("ลบข้อมูลไปทั้งหมด {0} รายการ", deleteIds.Length.ToString("#,##0")));
				return Json(new { success = true });
			}
			catch (Exception ex)
			{
				ModelState.AddModelError(ErrorLocalization.Error, ErrorLocalization.ErrorWhileDeleteData);
				GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
				return Json(new { success = false });
			}
		}

        public ActionResult GetProjectOperationExpense(int Id)
        {
            var sProjOper = new ProjectOperationService.ProjectOperationServiceClient();
            var result = sProjOper.SelectListExpense(new Models.BGM.ProjectOperationExpense() { ProjOperId = Id, RecordStatus = "!D" });
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetProjectOperationExpenseInfo(int Id)
        {
            var sProjOper = new ProjectOperationService.ProjectOperationServiceClient();
            var result = sProjOper.SelectExpense(new Models.BGM.ProjectOperationExpense() { ProjOperExpId = Id, RecordStatus = "!D" }, new[] { "ProjectExpense" }).FirstOrDefault();
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetResourceTypeInfo(int ProjOperExpId)
        {
            var sProjOper = new ProjectOperationService.ProjectOperationServiceClient();
            var sMasRes = new MasResourceService.MasResourceServiceClient();
            var ProjOperExpModel = sProjOper.SelectExpense(new Models.BGM.ProjectOperationExpense() { ProjOperExpId = ProjOperExpId, RecordStatus = "!D" }
                , new[] { "ProjectExpense" }).FirstOrDefault();
            var ResItemId = ProjOperExpModel.ProjectExpense.ResItemId;

            if (ResItemId.HasValue)
            {
                var result = sProjOper.SelectExpense(new Models.BGM.ProjectOperationExpense() { ProjOperExpId = ProjOperExpId, RecordStatus = "!D" }
                    , new[] { "ProjectExpense.MasResourceItem.MasResourceSubGroup"
                        , "ProjectExpense.MasResourceItem.MasResourceSubGroup.MasResourceGroup"
                        , "ProjectExpense.MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType"
                        , "ProjectExpense.MasResourceItem.MasUnit" }).FirstOrDefault();
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            else
            {
                var result = sMasRes.SelectResourceType(new Models.ICM.MasResourceType() { ResTypeId = 1, RecordStatus = "!D" }, null).FirstOrDefault();
                /*dynamic result2 = new
                {
                    result.AmountOfGroup, result.Code,
                    result.CreatedBy,
                    result.CreatedWhen,
                    result.DepreciationCalculate,
                    result.Descr,
                    result.Name,
                    result.RecordStatus,
                    result.ResTypeId,
                    result.UpdatedBy,
                    result.UpdatedWhen,
                    ProjOperExpModel.ProjectExpense
                }; */

                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult GetResourceGroupList(int ResTypeId, int? ResGrpId = null)
        {
            var sMasRes = new MasResourceService.MasResourceServiceClient();
            var result = sMasRes.SelectListResourceGroup(new Models.ICM.MasResourceGroup() { ResTypeId = ResTypeId, RecordStatus = "!D"});

            if (ResGrpId != null)
            {
                for (int i = 0; i < result.Length; i++)
                {
                    if (ResGrpId.ToString() == result[i].Value)
                    {
                        result[i].Selected = true;
                        break;
                    }
                }
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetResourceSubGroupList(int ResGrpId)
        {
            var sMasRes = new MasResourceService.MasResourceServiceClient();
            var result = sMasRes.SelectListResourceSubGroup(new Models.ICM.MasResourceSubGroup() { ResGrpId = ResGrpId, RecordStatus = "!D" });
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetResourceItemList(int ResSubGrpId)
        {
            var sMasRes = new MasResourceService.MasResourceServiceClient();
            var result = sMasRes.SelectListResourceItem(new Models.ICM.MasResourceItem() { ResSubGrpId = ResSubGrpId, RecordStatus = "!D" });

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetResourceItemInfo(int Id)
        {
            var sMasRes = new MasResourceService.MasResourceServiceClient();
            var result = sMasRes.SelectResourceItem(new Models.ICM.MasResourceItem() { ResItemId = Id, RecordStatus = "!D" }, new[] { "MasUnit" }).FirstOrDefault();

            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}
